package org.ajax.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.ajax.dao.GoodDao;
import org.ajax.dao.impl.GoodDaoImpl;
import org.ajax.entity.Good;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 查询所有商品
 *
 * @author ZQX
 * @date 2024-11-18
 */
@WebServlet("/table-demo/list_good.do")
public class ListGoodServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 设置响应内容类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        // 实例化 DAO 对象，执行数据库操作 - 查询所有的商品
        GoodDao goodDao = new GoodDaoImpl();
        List<Good> list = goodDao.selectGood();

        // 把 Java 对象转换为 JSON 字符串 - 序列化
        // 1.实例化 Gson 对象，并设置日期时间格式
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd")
                .create();

        // 2.序列化
        String json = gson.toJson(list);

        // 3.响应数据
        out.print(json);

        out.flush();
        out.close();

    }
}
